const express = require("express");
const pool = require("../pool.js");
//使用理由器
var router = express.Router();

//获取用户购物车列表
router.get("/shopping_list", (req, res) => {
  var _uid = req.query.uid;
  var sql = "SELECT * FROM shopping WHERE uid=?";
  pool.query(sql, _uid, (err, result) => {
    if (err) throw err;
    res.send(result);
  })
})
//增加
router.post("/add", (req, res) => {
  var obj = req.body;
  var sql = "insert into shopping set ?"
  pool.query(sql, obj, (err, result) => {
    if (err) throw err;
    if (result.affectedRows > 0) {
      res.send({
        "code": 200,
        "msg": "添加成功"
      });
    } else {
      res.send({
        "code": 301,
        "msg": "添加失败"
      });
    }
  })
})
//获取分页路由
router.get("/list", (req, res) => {
  var obj = req.query;
  var _page = obj.page;
  var _size = obj.size;
  if (!_page) {
    _page = 1;
  }
  if (!_size) {
    _size = 10;
  }
  //计算从第几条数据开始
  _page = (_page - 1) * _size;
  //把字符串转化为整数
  _page = parseInt(_page);
  _size = parseInt(_size);

  var sql = "SELECT * FROM shopping LIMIT ?,?";
  pool.query(sql, [_page, _size], (err, result) => {
    if (err) throw err;
    res.send(result);
  });
});
//删除
router.get("/delete", (req, res) => {
  var _shopid = req.query.shopid;
  var sql = "DELETE FROM shopping WHERE shopid=?";
  pool.query(sql, _shopid, (err, result) => {
    if (err) throw err;
    if (result.affectedRows > 0) {
      res.send({
        "code": 200,
        "msg": "删除成功"
      });
    } else {
      res.send({
        "code": 301,
        "msg": "删除失败"
      });
    }
  })
})
//获取详情
router.get("/details", (req, res) => {
  var _shopid = req.query.shopid;
  var sql = "SELECT * FROM shopping WHERE shopid=?";
  pool.query(sql, _shopid, (err, result) => {
    if (err) throw err;
    if (result.length) {
      res.send(result);
    } else {
      res.send({
        "code": 301,
        "msg": "查询失败"
      })
    }
  })
})
//编辑
router.post("/update", (req, res) => {
  var obj = req.body;
  for (var key in obj) {
    if (!obj[key]) {
      res.send({
        "code": 301,
        "msg": key + "不能为空"
      })
      return;
    }
  }
  var _shopid = obj.shopid;
  delete obj.shopid;
  var sql = "UPDATE shopping SET ? WHERE shopid=?";
  pool.query(sql, [obj, _shopid], (err, result) => {
    if (err) throw err;
    if (result.affectedRows > 0) {
      res.send({
        "code": 200,
        "msg": "修改成功"
      })
    } else {
      res.send({
        "code": 301,
        "msg": "修改失败"
      })
    }
  })
})

//改变购物车商品数量
router.post("/upcount",(req,res)=>{
	var obj = req.body;
	var _shopid = obj.shopid;
	var _count = obj.count;
	pool.query("UPDATE shopping SET count=? WHERE shopid=?",[_count,_shopid],(err,result)=>{
		if(err) throw err;
		if (result.affectedRows > 0) {
      res.send({
        "code": 200,
        "msg": "修改成功"
      })
    } else {
      res.send({
        "code": 301,
        "msg": "修改失败"
      })
    }
	})
})


//导出路由器
module.exports = router;